package com.warm.jpa.repository;


import com.warm.jpa.entity.BaseUserEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public interface BaseUserRepository extends JpaRepository<BaseUserEntity, String>, JpaSpecificationExecutor<BaseUserEntity> {

    /**
     * jpa 自定义 jpql --> 两种取参数的方式
     */
    @Transactional
    @Modifying
    @Query("update BaseUserEntity u set u.name = :name where u.id = :id")
    void updateById1(@Param("name") String name, @Param("id") String id);

    @Transactional
    @Modifying
    @Query("update BaseUserEntity u set u.name = ?1 where u.id = ?2")
    void updateById2(@Param("name") String name, @Param("id") String id);

    @Query(value = "select a from BaseUserEntity a where a.account = ?1")
    BaseUserEntity findByAccount(String account);

    /**
     * nativeQuery : 原生sql
     */
    @Query(
            value = "select * from jpa_example  where age = ?1",
            countQuery = "select count(*) from jpa_example where age = ?1",
            nativeQuery = true
    )
    Page<BaseUserEntity> findByAge(Integer age, Pageable pageable);

    Page<BaseUserEntity> findBySex(Integer sex, Pageable pageable);

    BaseUserEntity findByName(String name);

    List<BaseUserEntity> findByAgeGreaterThan(Integer age);

    /**
     * jpa 复杂查询 --> extends JpaSpecificationExecutor<JpaExampleEntity>
     *     接口可以多继承
     *     类只能单继承
     */
}

